package com.mobisys.live.controller.statisticcontroller;


import com.alibaba.fastjson.JSONObject;
import com.mobisys.live.bean.Tencent.StatisticTencentBean;
import com.mobisys.live.config.Config;
import com.mobisys.live.dao.mapper.LiveStatisticMapper;
import com.mobisys.live.dao.model.Live;
import com.mobisys.live.dao.model.LiveStatistic;
import com.mobisys.live.dao.model.Video;
import com.mobisys.live.response.Response;
import com.mobisys.live.response.tencentcloud.LiveStatOutput;
import com.mobisys.live.response.tencentcloud.LiveStatResponse;
import com.mobisys.live.response.tencentcloud.OutputStreamInfo;
import com.mobisys.live.response.tencentcloud.TencentEventResponse;
import com.mobisys.live.service.LiveService;
import com.mobisys.live.service.VideoService;
import com.mobisys.live.statistic.StatisticTask;
import com.mobisys.live.statistic.StatisticTencent;
import com.mobisys.live.util.SignUtil;
import com.mobisys.live.util.TimeUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import static com.mobisys.live.config.ResponseCode.*;

/*
* Created by liu
* 接受腾讯云的回调信息
*
* */
@RestController
public class TencentCloudController {
    @Autowired
    private LiveService liveService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private LiveStatisticMapper liveStatisticMapper;
    private Live live = new Live();
    private Response response = new Response();

    // 插入成功给腾讯云返回正确消息通知
    private JSONObject json = new JSONObject();
    private StatisticTencent statisticTencent = new StatisticTencent();
    private StatisticTencentBean statisticTencentBean = new StatisticTencentBean();
    private Logger logger = LogManager.getLogger(TencentCloudController.class.getName());


    static private HashMap<String, Timer> hashMapTimer = new HashMap<String, Timer>();


    /*
    * 接受腾讯云传递的消息体
    * */
    @RequestMapping(value = "/tencent/statistic", method = RequestMethod.POST)
    public JSONObject getEvent(@RequestBody TencentEventResponse tencentEventResponse) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println("++++++++++++++++++++ 1 get message++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        //检测是否拿到消息
        if (tencentEventResponse == null) {

            response.setRetureValue(TENCENT_EVENT_ERROR);
            response.setRetureMsg(MSG_TENCENT_EVENT_ERROR);
            return null;
        }


        switch (tencentEventResponse.getEvent_type()) {
            //断流事件
            case 0:
                logger.debug("断流相关信息 + pull + ：" + tencentEventResponse.toString());
                //断流更新live表
                int i = liveService.updateByliveId(tencentEventResponse.getStream_id().substring(5, 37), 0);
                if (i == 0) {
                    logger.debug("update is null ");
                    return null;
                }

                if (hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)) != null) {
                    hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)).cancel();
                }

                break;
            case 1:
                logger.debug("推流相关信息 + push +：" + tencentEventResponse.toString().trim());
                System.out.println("+++++++++++++++++++ 2  push stream+++++++++++++++++++++++++++++++++++++++++++");
                //推流更新live。
                int j = liveService.updateByliveId(tencentEventResponse.getStream_id().substring(5, 37), 1);
                if (j == 0) {
                    logger.debug("update is null ");
                    return null;
                }

                Timer timer = new Timer();
                hashMapTimer.put(tencentEventResponse.getStream_id().substring(5, 37), timer);

                //调用统计信息接口查询
                statisticTencentBean.setCmd(Integer.valueOf(Config.APP_ID));//设置参数
                String inter = "Get_LiveStat";//设置接口
                statisticTencentBean.setT((int) TimeUtil.getCurrentTimestamp());
                statisticTencentBean.setSign(SignUtil.md5sign(statisticTencentBean.getT(), Config.CALL_BACK_KEY));
                /*statisticTencentBean.setPage_no(1);
                statisticTencentBean.setPage_size(20);*/
                statisticTencentBean.setStream_id(tencentEventResponse.getStream_id());
                statisticTencentBean.setPull_domain(tencentEventResponse.getApp());


                timer.scheduleAtFixedRate(new TimerTask() {
                    public void run() {


                        try {
                            response = statisticTencent.getStatistic(statisticTencentBean, inter);
                        } catch (AWTException e) {
                            e.printStackTrace();
                        }

                        logger.debug("获取统计信息 ++++++++++++：" + response);

                        if (response.getRetureData() == null) {
                            System.out.println("++++++++++++++ message is null +++++++++++++++++++++++++++++++++++++++++++");
                            logger.debug("response.getRetureData() is null");
                            if (hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)) != null) {
                                hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)).cancel();
                            }
                            return;
                        }


                        //存储数据库
                        //存储数据库
                        LiveStatistic liveStatistic = new LiveStatistic();
                        System.out.println("++++++++++++++ 4 message is ture start insert ++++++++++++");
                        LiveStatResponse liveStatResponse = (LiveStatResponse) response.getRetureData();
                        List<LiveStatOutput> liveStatOutput = liveStatResponse.getOutput();
                        OutputStreamInfo outputStreamInfo = liveStatOutput.get(0).getStream_info().get(0);


                        liveStatistic.setLiveId(outputStreamInfo.getStream_name().substring(5, 37));
                        liveStatistic.setBandwidth(outputStreamInfo.getBandwidth());
                        liveStatistic.setBps(outputStreamInfo.getSpeed());
                        liveStatistic.setFps(outputStreamInfo.getFps());
                        liveStatistic.setOnline(outputStreamInfo.getOnline());
                        Date date = new Date();
                        try {
                             date = sdf.parse(sdf.format(new Date()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        liveStatistic.setTime(date);
                        logger.debug("liveStatstic " + liveStatistic.toString());

                        int k = liveStatisticMapper.insert(liveStatistic);
                        if (k == 0) {
                            response.setRetureValue(TENCENT_EVENT_ERROR);
                            response.setRetureMsg(MSG_TENCENT_EVENT_ERROR);

                        }
                    }
                }, 5000, 10000);

                break;
            case 100:
                logger.debug("录制最新消息 record ：" + tencentEventResponse.toString());
                if (hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)) != null) {
                    hashMapTimer.get(tencentEventResponse.getStream_id().substring(5, 37)).cancel();
                }

                //取出live相关信息
                live = liveService.selectByPrimaryKey(tencentEventResponse.getStream_id().substring(5, 37));
                if (live == null) {
                    logger.debug("select live is null");
                    return null;
                }
                //写入video
                Video video = new Video();
                video.setUserId(live.getUserId());
                video.setChannelId(live.getChannelid());
                video.setGroupid(live.getGroupid());
                video.setLiveId(live.getId());
                video.setPlayUrl(tencentEventResponse.getVideo_url());
                video.setIsDelete(Byte.parseByte("0"));
                video.setTitle(live.getTitle());
                video.setIntroduction("");
                video.setCoverPictureId(live.getCoverPictureId());
                video.setLikeCount(live.getLikeCount());
                video.setViewCount(live.getViewCount());
                video.setCreateTime(live.getCreateTime());
                video.setType(live.getType());
                video.setTag(live.getTag());
                video.settVideoId(tencentEventResponse.getVideo_id());
                video.settVideoUrl(tencentEventResponse.getVideo_url());
                video.settFileSize(tencentEventResponse.getFile_size());
                video.settStartTime(tencentEventResponse.getStart_time());
                video.settEndTime(tencentEventResponse.getEnd_time());
                video.settFileId(tencentEventResponse.getFile_id());
                video.settFileFormat(tencentEventResponse.getFile_format());
                video.settVod2flag(tencentEventResponse.getVod2Flag());
                video.settRecordFileId(tencentEventResponse.getRecord_file_id());
                video.settDuration(tencentEventResponse.getDuration());
                video.settStreamParam(tencentEventResponse.getStream_param());

                int n = videoService.insert(video);
                if (n > 0) {
                    logger.debug("点播数据插入数据库成功");

                } else {
                    logger.debug("插入数据库失败");

                }
                break;
        }
        response.setRetureValue(SUCCESS);
        response.setRetureMsg(MSG_SUCCESS);
        json.put("code", 0);


        logger.debug("get statistic message is success!!!!!!!!!!!!");
        return json;
    }


}
